What are Control Statements in C++?
Control Statements in C++ are used to control the flow of execution of a program. Normally, a program runs from top to bottom, but control statements allow us to make decisions and repeat actions.
C++ provides different types of control statements to handle situations like decision-making, looping, and jumping from one part of the program to another.
Types of Control Statements in C++:
- Decision Making Statements
- Looping Statements
- Jump Statements
Why Do We Need Control Statements?
- To make decisions in programs.
- To execute code only when a condition is true.
- To repeat tasks multiple times.
- To control program flow easily.
- To stop or skip execution when needed.
1. Decision Making Statements
These statements are used to make decisions based on conditions. The program executes different code depending on whether the condition is true or false.
Topics Covered:
Example:
#include <iostream>
using namespace std;
int main() {
int age = 18;
if (age >= 18) {
cout << "Eligible to vote";
}
return 0;
}
Output:
Eligible to vote
Explanation:
- The if statement checks the condition.
- If true, the code inside the block executes.
2. Looping Statements
These statements are used to repeat a block of code multiple times.
Topics Covered:
Example:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 3) {
cout << "Hello\n";
i++;
}
return 0;
}
Output:
Hello
Hello
Hello
Explanation:
- The while loop repeats the code while condition is true.
- Here, it runs 3 times (i = 1 to 3).
3. Jump Statements
These statements are used to change the flow of execution immediately.
Topics Covered:
Example:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
Output:
1
2
Explanation:
- The loop runs from 1 to 5.
- When i becomes 3, the break statement stops the loop.
- So only 1 and 2 are printed.
Summary:
- Control statements control the flow of execution in a program.
- They help in decision making, looping, and jumping.
- C++ provides different types like if, loops, and jump statements.
- They make programs dynamic and flexible.